import { login, setStorageSync } from '@tarojs/taro'
import { isFlutterApp } from 'taro-bridge'
import type { RequestOptions } from './types'
import { thirdAuth20AuthApi, thirdMpAuthApi } from '@/api/services/third'
import { AUTH_TICKET_KEY, R_A_TOKEN } from '@/constants/key'
import { browserJudgment } from '@/utils'
import { encrypt } from '@/utils/encrypt'
import { riskAccessTokenRefreshApi } from '@/api/services/risk'

export const genUniqueReqKey = (opts: RequestOptions) => {
  const { method, url, query, param } = opts

  return [method, url, JSON.stringify(query), JSON.stringify(param)].join('|')
}

/**
 * 保持二维码扫描地址中的q参数的encode
 * @param params
 */
export function processSpecialParams(params: Record<string, any>) {
  const result = {}
  Object.keys(params).forEach((key) => {
    const item = params[key]
    if (key === 'q')
      result[key] = encodeURIComponent(item)
    else
      result[key] = item
  })
  return result
}

/**
 * 根据url获取参数
 * @param name
 * @param url url 地址 eg. https://www.baidu.com?a=1&b=2
 */
export function getUrlParams(name: string, url: string) {
  const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i')
  let search
  if (url.includes('?'))
    search = url.split('?')[1].match(reg)

  else
    search = null

  if (search !== null)
    return unescape(search[2])
  return ''
}

export function getUserATicket() {
  if (process.env.TARO_ENV === 'weapp') {
    let jsCode = ''
    return login()
      .then((res) => {
        jsCode = res.code
        return thirdMpAuthApi({ query: { jsCode } }, { force: true })
      })
      .then((data) => {
        setStorageSync(AUTH_TICKET_KEY, data.ticket)
        return Promise.resolve({ code: jsCode })
      })
      .catch(() => { })
  }

  if (process.env.TARO_ENV === 'alipay') {
    return new Promise((resolve) => {
      // @ts-expect-error
      my.getAuthCode({
        scopes: ['auth_base'],
        success: (res) => {
          thirdAuth20AuthApi({ query: { code: res.authCode, authPlatform: 'ALI' } }, { force: true }).then((res) => {
            setStorageSync(AUTH_TICKET_KEY, res.ticket)
            resolve('SUCCESS')
          })
        },
      })
    })
  }

  if (process.env.TARO_ENV === 'h5') {
    if (browserJudgment() === 'weapp') {
      if (getUrlParams('code', window.location.href)) {
        return new Promise((resolve) => {
          thirdAuth20AuthApi({
            query: {
              code: getUrlParams('code', window.location.href),
              authPlatform: 'WECHAT',
            },
          }, { force: true }).then((res) => {
            setStorageSync(AUTH_TICKET_KEY, res.ticket)
            resolve('success')
          })
        })
      }
      else {
        const url = `${process.env.TARO_SERVER_URL}/zhongri/app/#/zhongri/app/pages/auth/index?url=${encodeURIComponent(window.location.href)}`
        window.location.href = url
      }
    }
  }
}
export function refreshToken(timestamp) {
  return new Promise((resolve) => {
    let sign = ''

    if (process.env.TARO_ENV === 'alipay' || isFlutterApp())
      sign = encrypt(`${process.env.TARO_HOS_CODE}€${timestamp}`)
    else
      sign = encodeURIComponent(encrypt(`${process.env.TARO_HOS_CODE}€${timestamp}`))

    riskAccessTokenRefreshApi({
      query: {
        timestamp,
        sign,
      },
    }, {
      force: true,
    }).then((data) => {
      if (data)
        setStorageSync(R_A_TOKEN, data)

      resolve(true)
    }).catch(() => {
      resolve(true)
    })
  })
}
